import useRequestTable from '@/hooks/useRequestTable';
// import useTableSelection from '@/hooks/useTableSelection';
import { ConfigProps } from '@/hooks/use-table-and-form-config/type';
import { FormatProps, OptionsType } from '@/hooks/useRequestTable';
import useTableSelection from '@/hooks/useTableSelection';
import type { FormInstance } from 'antd';
import { Table, TableProps } from 'antd';
import { forwardRef, useImperativeHandle } from 'react';
interface Props {
  form?: FormInstance;
  columns?: ConfigProps[];
  api?: any;
  submitFormat?: (params: any) => any;
  apiType?: 'GET' | 'POST';
  getTableData?: any;
  tableRest?: TableProps;
  hookRest?: OptionsType;
  showRowSelection?: boolean;
  formatResult?: (params: any) => FormatProps;
}
const RequestTable = (props: Props, ref: any) => {
  const {
    form,
    columns,
    tableRest,
    api = () => {},
    submitFormat = () => {},
    apiType = 'POST',
    showRowSelection = false,
    formatResult,
    hookRest,
  } = props;
  const { rowSelection, selectedRowKeys, selectIds } = useTableSelection();

  const getTableData = async (
    params: OptionsType['defaultPageParams'],
    formData: any,
  ) => {
    // console.log(params, formData, '参数,搜索表单参数');
    let obj = {
      ...params,
      ...formData,
    };
    if (typeof submitFormat === 'function') {
      obj = submitFormat(obj) || {};
    }
    const payload =
      apiType === 'POST'
        ? {
            data: {
              ...obj,
            },
          }
        : {
            params: {
              ...obj,
            },
          };
    return await api?.(payload);
  };

  const {
    tableProps,
    search: { submit, reset },
  } = useRequestTable(getTableData, {
    form,
    formatResult,
    ...hookRest,
  });

  useImperativeHandle(ref, () => {
    return {
      submit,
      reset,
      tableProps,
      selectedRowKeys,
      selectIds,
    };
  });

  return (
    <div>
      <Table
        rowKey={'id'}
        {...tableProps}
        rowSelection={showRowSelection ? rowSelection : undefined}
        columns={columns as any}
        {...tableRest}
      ></Table>
    </div>
  );
};
export default forwardRef(RequestTable);
